import logging
import sys

from producttest.caw.readfile import get_protectpath


class Logger:
    def __init__(self):
        #创建一个日志对象
        self.logger = logging.getLogger()
        # 设置级别
        self.logger.setLevel('INFO')

    # 对日志进行配置
    def console(self,message,level):
        # 日志在哪里写（文件写日志，在控制台写日志）
        # 处理器：FileHandler StreamHandler
        filepath = get_protectpath()+'\\logs\\'+'log.txt'
        fh = logging.FileHandler(filepath,mode='a',encoding='utf-8')

        # 日志的格式
        formatter =logging.Formatter("[%(asctime)s]-[%(filename)s]-[%(levelname)s]:%(message)s")
        fh.setFormatter(formatter)

        self.logger.addHandler(fh)

        # 控制台日志
        sysh = logging.StreamHandler(sys.stdout)
        sysh.setFormatter(formatter)
        self.logger.addHandler(sysh)

        if level == "debug":
            self.logger.debug(message)
        elif level == "info":
            self.logger.info(message)
        elif level == "warning":
            self.logger.warning(message)
        elif level == "error":
            self.logger.error(message)
        elif level == "critical":
            self.logger.critical(message)

        # 为了避免重复打印日志，要移除处理器
        self.logger.removeHandler(fh)
        self.logger.removeHandler(sysh)

        #关闭处理器
        fh.close()

    def debug(self,message):
        self.console(message,level="info")

    def info(self,message):
        self.console(message,level="info")

    def warning(self, message):
        self.console(message, level="info")

    def error(self, message):
        self.console(message, level="info")

    def critical(self, message):
        self.console(message, level="info")

    # 写日志  写的日志内容，日志的级别

if __name__ == '__main__':
    logger = Logger()
    logger.debug("this is debug")
    logger.info("this is info")
    logger.error("this is error")